//
//  Employees.swift
//  AdapterPattern
//
//  Created by LY on 2017/9/28.
//  Copyright © 2017年 DesignPatterns. All rights reserved.
//

import Foundation

struct Employee {
    var name : String
    var title : String
}

protocol EmployeeDataSource {
    var employees:[Employee] {get}
    func searchByName(name:String) -> [Employee]
    func searchByTitle(title:String)-> [Employee]
}
class DataSourceBase: EmployeeDataSource {
    func searchByName(name: String) -> [Employee] {
       return  search { (e) -> Bool in
            return e.name.rangeOfCharacter(from: CharacterSet(charactersIn: name)) != nil
        }
    }
    
    func searchByTitle(title: String) -> [Employee] {
        return search(selector: { (e) -> Bool in
            return e.title.rangeOfCharacter(from: CharacterSet(charactersIn: title)) != nil
        })
    }
    
    private func search(selector:((Employee) -> Bool)) -> [Employee]{
        var results = [Employee]()
        for e in employees {
            if(selector(e)){
                results.append(e)
            }
        }
        return results
    }
    
    var  employees: [Employee] = [Employee]()
    
}

class SalesDataSource: DataSourceBase {
    override init() {
        super.init()
        employees.append(Employee(name: "Alice", title: "VP of Sales"))
        employees.append(Employee(name: "Bob", title: "Account Exec"))
    }
}
class DevelopmentDataSource: DataSourceBase {
    override init() {
        super.init()
        employees.append(Employee(name: "Joe", title: "VP of Development"))
        employees.append(Employee(name: "Pepe", title: "Developer"))
    }
}

class SearchTool {
    enum SearchType {
        case Name
        case TITLE
    }
    private let sources : [EmployeeDataSource]
    init(dataSource:EmployeeDataSource...) {
        self.sources = dataSource
    }
    var employees:[Employee]{
        var results = [Employee]()
        for source in sources{
            results += source.employees
        }
        return results
    }
    func allEmployees() -> [Employee]{
        var results = [Employee]()
        for source in sources{
            results += source.employees
        }
        return results
    }
    func search(text:String,type:SearchType) -> [Employee]{
        var results = [Employee]()
        for source in sources{
            results += type == SearchType.Name ? source.searchByName(name: text):source.searchByTitle(title: text)
        }
        return results
    }
}




